#include "role_activity.h"
#include "Player.h"

#include "../share/tplmgr.h"
#include "../share/time_module.h"

CRoleActivity::CRoleActivity( )
{
	role_activity_data_.clear();
}

CRoleActivity::~CRoleActivity( )
{

}

bool CRoleActivity::ReadFromJson(const Json::Value& data_json)
{
	for ( int32_t i = 0; i < data_json.size(); ++i )
	{
		Json::Value one_activity = data_json[i];
		int32_t activity_id = one_activity["activity_id"].asInt();
		int32_t join_time = one_activity["join_time"].asInt();
		TActivityDataMap::iterator it = role_activity_data_.find(activity_id);
		if (it == role_activity_data_.end())
		{
			CActivityCount act_count;
			act_count.set_activity_id(activity_id);
			act_count.set_join_time(join_time);
			role_activity_data_[activity_id] = act_count;
		}
	}
	return true;
}

bool CRoleActivity::WriteToJson(Json::Value& data_json)
{
	for (TActivityDataMap::iterator it = role_activity_data_.begin(); it != role_activity_data_.end(); ++it )
	{
		Json::Value one_activity;
		one_activity["activity_id"] = (int32_t)it->second.activity_id();
		one_activity["join_time"] = (int32_t)it->second.join_time();
		
		data_json.append(one_activity);
	}
	return true;
}

int32_t CRoleActivity::GetJoinTimes(int32_t activity_id)
{
	TActivityDataMap::iterator it = role_activity_data_.find(activity_id);
	if ( it == role_activity_data_.end() )
	{
		return 0;
	}
	return it->second.join_time();
}

void CRoleActivity::AddJoinTime(int32_t activity_id)
{
	TActivityDataMap::iterator it = role_activity_data_.find(activity_id);
	if (it == role_activity_data_.end())
	{
		CActivityCount act_count;
		act_count.set_activity_id(activity_id);
		act_count.set_join_time(1);
		role_activity_data_[activity_id] = act_count;
	}
	else
	{
		role_activity_data_[activity_id].activity_id_ = activity_id;
		role_activity_data_[activity_id].join_time_ ++;
		role_activity_data_[activity_id].timestamp_ = CUR_SEC;
	}
}

void CRoleActivity::onNewDay(Player& player)
{
	role_activity_data_.clear();
}


int32_t CRoleActivity::ValidJoinTime(int32_t activity_id)
{
	TActivityDataMap::iterator it = role_activity_data_.find(activity_id);
	if (it == role_activity_data_.end())
	{
		return ::common::SUCCEED;
	}
	
	if ((CUR_SEC - it->second.timestamp_  ) <100)
	{
		return ::common::ERR_OP_REPEAT;
	}
	return ::common::SUCCEED;
}